package com.reader.cms.controller.sys;

import com.reader.cms.controller.BaseController;
import com.reader.cms.entity.sys.SysToken;
import com.reader.cms.entity.sys.SysUser;
import com.reader.cms.mapper.sys.SysUserMapper;
import com.reader.cms.service.sys.ISysTokenService;
import com.reader.core.entity.ResultMessageInfo;
import com.reader.core.utils.CommonVariable;
import com.reader.core.utils.ValidatorUtil;
import com.reader.core.validator.group.AddGroup;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


/**
 * Created by jiahaikun on 2018/11/05
 */
@RestController
@RequestMapping(value = "/api/sys/")
public class SysLoginController extends BaseController<Object> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysTokenService iSysTokenService;

    /**
     * 登录
     *
     * @return 登录成功后 带回token信息
     * @param登录
     */
    @PostMapping("login")
    @ResponseBody
    @ApiOperation(value = "用户-登录", notes = "用户登录")

    public ResultMessageInfo login(@RequestBody SysUser user){
        ValidatorUtil.validateEntity(user, AddGroup.class);//非空验证
        String loginId =user.getLoginId();
        String password = user.getPassword();

        try{
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginId, password);
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e) {
            return ResultMessageInfo.ofMessage(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            iSysTokenService.plusRetry(loginId);   //此外异常为密码错误，redis token重试次数增加一次
            return ResultMessageInfo.ofMessage("账号或密码不正确");
        }catch (LockedAccountException e) {
            return ResultMessageInfo.ofMessage("账号已被锁定,请联系管理员");
        }catch (AuthenticationException e) {
            return ResultMessageInfo.ofMessage("账户验证失败");
        }

         //要用loginid 取到userid然后再生成token
        //放到Token对象返回到前端
        SysToken token=iSysTokenService.getTokenInfoByLoginId(loginId);
        token.setUserID(null);
        token.setRetryLoginCnt(null);
        token.setLoginId(null);
        token.setUserAgent(null);
        iSysTokenService.initRetry(loginId);//登录成功，则尝试登录数据恢复为0
        return ResultMessageInfo.ofSuccess("登录成功！",token);
    }


    /**
     * 退出
     *
     * @return
     */
    @PostMapping("logout")
    @ResponseBody
    public ResultMessageInfo logout() {
        String token = request.getHeader(CommonVariable.TOKEN);
        Integer userId=getUserId();
        SecurityUtils.getSubject().logout();
        iSysTokenService.expireToken(token);
        ResultMessageInfo resultMessage = this.getSuccessResultMessage("登出成功!",null);
        //将登陆信息保存到数据库
        return resultMessage;
    }

}
